<template>
    <van-sticky>
        <van-nav-bar title="确认订单" left-text="返回" left-arrow @click-left="onBack">
        </van-nav-bar>
    </van-sticky>

    <van-contact-card type="add" @click="ToAddress" v-if="addressDefault.hasOwnProperty('id') === false" />
    <van-contact-card type="edit" :tel="addressDefault.mobile" :name="addressDefault.consignee" @click="ToAddress"
        v-else />

    <van-card v-for="item in CartList" :key="item.id" :num="item.nums" :price="item.total" :title="item.product.name">
        <template #thumb>
            <van-image width="88" height="88" fit="cover" :src="item.product.thumb_cdn" />
        </template>

        <template #desc>
            <div>
                商品单价：{{ item.product.price }}
            </div>
        </template>
        <template #tags>
            <van-tag plain type="danger" v-if="!item.attrs">无商品规格</van-tag>
            <div v-else>
                <van-tag plain type="primary" v-for="attr in JSON.parse(item.attrs)" :key="attr.id">{{ attr.value
                    }}</van-tag>
            </div>
        </template>
    </van-card>

    <van-cell title="支付方式" :value="PayActive.text" is-link @click="PayShow = true" />
    <!-- PayActive.text选中的值， -->

    <van-popup v-model:show="PayShow" round position="bottom">
        <van-picker title="选择支付方式" :columns="PayList" @cancel="PayShow = false" @confirm="onPayConfirm" />
        <!-- @confirm="onPayConfirm"确认选择哪种支付方式  -->
    </van-popup>

    <!-- 优惠券单元格 -->
    <van-coupon-cell :coupons="CouponList" :chosen-coupon="CouponActive" @click="CouponShow = true" />

    <!-- 优惠券列表 -->
    <van-popup v-model:show="CouponShow" round position="bottom" style="height: 90%; padding-top: 4px;">
        <van-coupon-list :coupons="CouponList" :chosen-coupon="CouponActive" :exchange-button-disabled="true"
            :show-exchange-bar="false" @change="onCouponChange" />
    </van-popup>

    <!--订单备注 -->
    <van-field v-model="remark" rows="2" autosize label="订单备注" type="textarea" maxlength="120" placeholder="请输入订单备注"
        show-word-limit />

    <!-- 提交动作栏 -->
    <van-submit-bar text-align="left" :price="total" button-text="确认支付" @submit="onSubmit" />

</template>

<script setup>
const { proxy } = getCurrentInstance();
const addressDefault = ref({});
const remark = ref("");
const CartList = ref([]);
const cartids = ref(proxy.$route.query.cartids ?? 0)
const source = ref(proxy.$route.query.source ?? 0)
const business = proxy.$cookies.get('business').id;
const PayShow = ref(false);
const PayList = ref([
    { text: '余额支付', value: 'money' },
    { text: '支付宝支付', value: 'zfb' },
    { text: '微信支付', value: 'wx' }
]);
const PayActive = ref(PayList.value[0]);
//确认支付
const onPayConfirm = ({ selectedOptions }) => {
    PayActive.value = selectedOptions[0];

    PayShow.value = false;
}

// 优惠券
const CouponShow = ref(false); //是否显示优惠卷
const CouponList = ref([]);// 优惠券数据
const CouponActive = ref(-1);// 选择优惠券索引
//选择优惠卷
const onCouponChange = (index) => {
    CouponActive.value = index;

    CouponShow.value = false;

    if (index !== -1) {
        let Total = 0;

        CartList.value.map(item => Total += parseFloat(item.total))

        let rate = CouponList.value[index].rate;

        let price = parseFloat(Total * rate).toFixed(2);

        let CouponPrice = Total - parseFloat(price);

        CouponList.value[index].value = CouponPrice * 100;  //计算优惠了多少

    }
}
//计算选择优惠卷之后的价钱
const total = computed(() => {
    let total = 0;

    if (CartList.value.length > 0) {
        for (let item of CartList.value) {
            total += parseFloat(item.total)
        }
    }

    if (CouponActive.value !== -1) {
        let CouponRate = CouponList.value[CouponActive.value].rate;
        console.log(CouponRate);
        total = total * parseFloat(CouponRate);
        console.log(total);
        console.log(parseFloat(CouponRate));
    }

    return total * 100;
})
//获取优惠卷数据
const getCouponData = async () => {
    let params = {
        busid: business
    }

    let result = await proxy.$post({
        url: '/product/order/coupon',
        params
    })

    if (result.code === 1) {
        for (let item of result.data) {
            CouponList.value.push({
                id: item.id,
                name: item.coupon.title,
                condition: item.coupon.status_text,
                startAt: item.coupon.createtime,
                endAt: item.coupon.endtime,
                rate: item.coupon.rate,
                valueDesc: `${item.coupon.rate * 10}`,
                unitDesc: '折',
            })
        }
    }
}

onBeforeMount(() => {
    getCartListData();

    getCouponData();

    // 获取当前用户选择的收货地址
    let address = proxy.$cookies.get('address');

    if (address) {
        addressDefault.value = address;
    } else {
        getAddressDefaultInfo();
    }
})

const onSubmit = async () => {
    let params = {
        busid: proxy.$business.value.id,
        addrid: addressDefault.value.id,
        cartids: cartids.value,
        pay: PayActive.value.value,
        remark: remark.value         //备注
    }

    if (CouponActive.value !== -1) {
        // 用户领取优惠券的id
        params.couponid = CouponList.value[CouponActive.value].id
    }

    let result = await proxy.$post({
        url: '/product/order/add',
        params
    });

    if (result.code === 1) {
        proxy.$NotifySuccess({
            msg: result.msg,
            onClose: () => {
                proxy.$router.push('/product/order/index');
            }
        });
    } else {
        proxy.$NotifyWarn(result.msg)
    }
}

onBeforeUnmount(() => {
    proxy.$cookies.remove('address');
})

//从购物车处选择的商品
const getCartListData = async () => {
    let params = {
        busid: business,
        cartids: cartids.value
    }

    let result = await proxy.$post({
        url: '/product/order/cart',
        params
    })
    console.log(result);

    if (result.code === 1) {
        CartList.value = result.data;
        return false;
    } else {
        proxy.$NotifyWarn({
            msg: result.msg,
            onClose: () => onBack
        })

        return false;
    }
}
//通过直接购买跳转到该页面


//跳转到地址页面
const ToAddress = () => {
    proxy.$router.push({ path: '/business/address/index', query: { action: 'order' } })
}

//地址设置
const getAddressDefaultInfo = async () => {
    let params = {
        busid: proxy.$business.value.id
    }

    let result = await proxy.$post({
        url: '/product/order/address',
        params
    })

    if (result.code === 1) {
        addressDefault.value = result.data;

        return false;
    } else {
        proxy.$NotifyWarn(result.msg);

        return false;
    }
}

const onBack = async () => {
    if (source.value == 1) {
        let params = {
            cartids: cartids.value,
            busid: business,
            source: source.value
        }
        let result = await proxy.$post({
            url: 'product/cart/del',
            params
        })

        if (result.code === 1) {
            proxy.$router.back();
        } else {
            proxy.$NotifyWarn(result.msg);
        }
    } else {
        proxy.$router.back();
    }
}
</script>